<template>
  <div class="home-container">
    <!-- 右上角图标导航 -->
    <div class="top-nav-icons">
      <div class="nav-icon" @click="settingConfig" title="设置">
        <el-icon>
          <Setting />
        </el-icon>
      </div>
    </div>
    <!-- 头部筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-select v-model="queryParams.type" placeholder="选择类型" clearable @change="handleSearch">
            <el-option label="全部" :value="null" />
            <el-option label="视频" :value="BookmarkType.VIDEO" />
            <el-option label="博客" :value="BookmarkType.BLOG" />
            <el-option label="音乐" :value="BookmarkType.MUSIC" />
            <el-option label="其他" :value="BookmarkType.OTHER" />
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-input v-model="queryParams.keyword" placeholder="搜索标题或标签" clearable @keyup.enter="handleSearch">
            <template #append>
              <el-button @click="handleSearch" :icon="Search">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="sortParams" placeholder="排序方式" @change="handleSearch">
            <el-option label="创建时间(新到旧)" value="create_time,desc" />
            <el-option label="创建时间(旧到新)" value="create_time,asc" />
            <el-option label="更新时间(新到旧)" value="update_time,desc" />
            <el-option label="更新时间(旧到新)" value="update_time,asc" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 收藏列表 -->
    <div v-else class="bookmark-grid">
      <div v-for="bookmark in bookmarkList" :key="bookmark.id" class="bookmark-card">
        <el-card shadow="hover" class="card-item">
          <!-- 置顶标识 -->
          <div v-if="bookmark.isTop === 1" class="top-badge">
            <el-tag type="warning" size="small">置顶</el-tag>
          </div>

          <!-- Logo和标题区域 -->
          <div class="card-header" @click="openBookmark(bookmark.url)">
            <div class="logo-container">
              <img v-if="bookmark.logoUrl" :src="bookmark.logoUrl" :alt="bookmark.title" class="bookmark-logo"
                @error="handleImageError" />
              <div v-else class="default-logo">
                <el-icon :size="32">
                  <Link />
                </el-icon>
              </div>
            </div>
            <div class="title-container">
              <h3 class="bookmark-title" :title="bookmark.title">
                {{ bookmark.title }}
              </h3>
              <p class="bookmark-url" :title="bookmark.url">
                {{ bookmark.url }}
              </p>
            </div>
          </div>

          <!-- 描述信息 -->
          <div v-if="bookmark.description" class="card-content">
            <p class="bookmark-description">{{ bookmark.description }}</p>
          </div>

          <!-- 标签和类型 -->
          <div class="card-footer">
            <div class="tags-container">
              <el-tag v-if="bookmark.tags" size="small" type="info" class="tag-item">
                {{ bookmark.tags }}
              </el-tag>
              <el-tag :type="getTypeTagType(bookmark.type)" size="small" class="type-tag">
                {{ getTypeName(bookmark.type) }}
              </el-tag>
            </div>
            <div class="time-info">
              <span class="create-time">{{ formatTime(bookmark.createTime) }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && bookmarkList.length === 0" class="empty-container">
      <el-empty description="暂无收藏数据" />
    </div>

    <!-- 分页组件 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.size" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Link, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBookmarkList,
  BookmarkType,
  BookmarkTypeName,
  BookmarkTypeTagType
} from '@/api/bookmark/bookmark'
import { getBaseURL, setBaseURL } from '@/utils/request'

// 响应式数据
const loading = ref(false)
const bookmarkList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 20,
  type: null,
  keyword: '',
  sortBy: 'create_time',
  sortOrder: 'desc'
})

// 排序参数
const sortParams = ref('create_time,desc')

// 获取收藏列表
const getBookmarkListData = async () => {
  loading.value = true
  try {
    const [sortBy, sortOrder] = sortParams.value.split(',')
    const params = {
      ...queryParams,
      sortBy,
      sortOrder
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === '') {
        delete params[key]
      }
    })

    const response = await getBookmarkList(params)

    if (response.data.code === 200) {
      bookmarkList.value = response.data.data.list || []
      total.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  queryParams.page = 1
  getBookmarkListData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  getBookmarkListData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  queryParams.page = page
  getBookmarkListData()
}

// 打开收藏链接
const openBookmark = (url) => {
  if (url) {
    window.open(url, '_blank')
  }
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.style.display = 'none'
  event.target.nextElementSibling.style.display = 'flex'
}

// 获取类型名称
const getTypeName = (type) => {
  return BookmarkTypeName[type] || '其他'
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  return BookmarkTypeTagType[type] || 'info'
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const settingConfig = () => {
  ElMessageBox.prompt('请输入服务器IP和端口', '设置', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputValue: 'http://tt.xwbb.top',
  })
    .then(({ value }) => {
      setBaseURL(value)
      ElMessage({
        type: 'success',
        message: `地址是:${value}`,
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}

// 组件挂载时获取数据
onMounted(() => {
  getBookmarkListData()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.filter-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container {
  padding: 20px;
}

.bookmark-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.bookmark-card {
  position: relative;
}

.card-item {
  height: 100%;
  transition: transform 0.2s ease-in-out;
  cursor: pointer;
}

.card-item:hover {
  transform: translateY(-2px);
}

.top-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
}

.card-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.logo-container {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  position: relative;
}

.bookmark-logo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.default-logo {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  color: #909399;
}

.title-container {
  flex: 1;
  min-width: 0;
}

.bookmark-title {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bookmark-url {
  margin: 0;
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-content {
  margin-bottom: 12px;
}

.bookmark-description {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.tags-container {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.tag-item {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.type-tag {
  flex-shrink: 0;
}

.time-info {
  font-size: 12px;
  color: #c0c4cc;
  flex-shrink: 0;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home-container {
    padding: 12px;
  }

  .bookmark-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .filter-section .el-row {
    flex-direction: column;
    gap: 12px;
  }

  .filter-section .el-col {
    width: 100% !important;
  }
}

/* 右上角图标导航样式 */
.top-nav-icons {
  position: fixed;
  top: 20px;
  right: 20px;
  display: flex;
  gap: 15px;
  z-index: 1000;
}

.nav-icon {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

@media (max-width: 1200px) {
  .bookmark-grid {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
}
</style>
